package doan.chuyennganh.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import doan.chuyennganh.base.DoAnBaseAcitvity;
import doan.chuyennganh.base.RequestUI;
import doan.chuyennganh.model.Attendance;
import doan.chuyennganh.model.AttendanceList;
import doan.chuyennganh.model.ClassStudent;
import doan.chuyennganh.model.ListClass;
import doan.chuyennganh.model.ListStudent;
import doan.chuyennganh.model.SavedAttendanceDataReturnObject;
import doan.chuyennganh.model.Student;
import doan.chuyennganh.util.Constants;

public class HomeActivity extends DoAnBaseAcitvity implements OnClickListener {
	private TextView tvNumberStudentBanned;
	private TextView tvLastUpdate;
	private ListView lvListStudentBanned;
	private Button btnComite;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_activity);
		tvNumberStudentBanned = (TextView) findViewById(R.id.tv_testing_ban_students_title);
		tvLastUpdate = (TextView) findViewById(R.id.tv_last_time_update);
		lvListStudentBanned = (ListView) findViewById(R.id.lv_list_student_banned);
		btnComite = (Button) findViewById(R.id.btn_comite);
		btnComite.setOnClickListener(this);
		init();
	}

	public void init() {
		String time = pre.getString(String.format(
				Constants.PREFERENCE_LAST_TIME_UPDATE, ListStudent
						.getInstance().getClassID()),
				getString(R.string.txt_unknow));
		tvLastUpdate.setText(String.format(getString(R.string.txt_last_update),
				time));
		ArrayList<String> items = null;

		AttendanceList attendanceList = ListStudent.getInstance()
				.getAttendanceList();
		String classID = ListStudent.getInstance().getClassID();
		ClassStudent cls = ListClass.getInstance().getClass(classID);

		if (attendanceList != null && cls != null) {
			int tst = cls.getTongsotiet();
			items = attendanceList.absenceOverRate(tst, Constants.BANNED_RATE);// ListStudent.getInstance().getAttendanceList().absenceOverRate(LeftMenuListFragment.listClass.getClass(ListStudent.getInstance().getClassID()).getTongsotiet(),
																				// Constants.BANNED_RATE);
		}

		if (items != null && items.size() > 0) {
			ArrayList<String> fullItems = new ArrayList<String>();
			for(String id : items){
				Student stu = ListStudent.getInstance().getStudent(id);
				if(stu != null)
				fullItems.add( stu.getMaSV()+ " - " + stu.getHoten() + " - " + stu.getLop());
			}
			
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					R.layout.list_item, fullItems);
			lvListStudentBanned.setAdapter(adapter);

			lvListStudentBanned.setVisibility(View.VISIBLE);
			tvNumberStudentBanned.setText(String.format(
					getString(R.string.txt_number_student_testing_banned),
					fullItems.size() + " sv"));
		} else {
			lvListStudentBanned.setVisibility(View.GONE);
			tvNumberStudentBanned.setText(String.format(
					getString(R.string.txt_number_student_testing_banned),
					getString(R.string.txt_unknow)));
		}

	}

	private void CommiteData(ListStudent listStudent) {
		AttendanceList attendanceList = listStudent.getAttendanceList();
		JSONArray sendObject = new JSONArray();
		JSONArray data = new JSONArray();
		JSONObject cls = new JSONObject();
		try {

			for (int i = 0; i < attendanceList.size(); i++) {
				Attendance att = attendanceList.get(i);
				JSONObject tmp = new JSONObject();
				tmp.put("ngay", att.getDate());
				tmp.put("sotiet", att.getPeriod());
				ArrayList<String> listdata = att.getAllStudentAttendanced();
				JSONArray list = new JSONArray();

				for (String s : listdata) {
					JSONObject sv = new JSONObject();
					sv.put("mssv", s);
					list.put(sv);
				}
				tmp.put("list", list);
				data.put(tmp);
			}

			cls.put("malop", listStudent.getClassID());
			cls.put("data", data);
			sendObject.put(cls);
		} catch (JSONException e) {
			btnComite.setEnabled(true);
			e.printStackTrace();
		}
		String senddata = sendObject.toString();
		SendingAttendanceData request = new SendingAttendanceData(
				Constants.SERVICE_UPDATE_TO_SERVER, this, senddata);
		getRequestQueue().addRequest(request);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_comite:
			btnComite.setEnabled(false);
			Toast.makeText(this, getString(R.string.txt_updating), Toast.LENGTH_LONG).show();
			CommiteData(ListStudent.getInstance());
			break;

		default:
			break;
		}
	}

	@SuppressLint("SimpleDateFormat")
	private String getTodayFormatString() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("hh:mm - dd/MM/yyyy");
		return df.format(c.getTime());
	}

	class SendingAttendanceData extends RequestUI {
		private String data;
		private SavedAttendanceDataReturnObject result;

		public SendingAttendanceData(Object key, Activity activity, String data) {
			super(key, activity);
			this.data = data;
		}

		@Override
		public void execute() throws Exception {
			result = daApi.SendingAttendanceData(data);
		}

		@Override
		public void executeUI(Exception ex) {
			btnComite.setEnabled(true);
			if (result != null && result.getError_code() != -1) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.txt_saved_data_to_server_success),
						Toast.LENGTH_LONG).show();
				String today = getTodayFormatString();
				tvLastUpdate.setText(String.format(getString(
						R.string.txt_last_update, today)));
				pre.putString(String.format(
						Constants.PREFERENCE_LAST_TIME_UPDATE, ListStudent
								.getInstance().getClassID()), today);
			} else {
				Toast.makeText(getApplicationContext(),
						getString(R.string.txt_saved_data_to_server_failed),
						Toast.LENGTH_LONG).show();
			}
		}

	}
}
